<template>
  <div class="page-container">
    <el-card class="main-card">
      <div slot="header" class="card-header">
        <span>商品分类</span>
        <div class="header-operations">
          <el-button type="primary" @click="handleAdd">添加分类</el-button>
        </div>
      </div>
      
      <el-table
        :data="categoryList"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
      >
        <el-table-column prop="name" label="分类名称" width="100" align="center"></el-table-column>
        <el-table-column prop="productNum" label="商品数量" width="240" align="center">
          <template slot-scope="scope">
            <el-tag size="small" type="info">{{ scope.row.productNum || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="库存总量" width="200" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getCategoryList,
  saveCategory,
  deleteCategory
} from '@/api/product'

export default {
  name: 'ProductCategory',
  data() {
    return {
      loading: false,
      categoryList: [],
      total: 0,
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: '添加分类',
      categoryForm: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    categoryOptions() {
      return this.categoryList.map(item => ({
        value: item.id,
        label: item.name
      }))
    }
  },
  methods: {
    // 获取分类列表
    async fetchCategories() {
      this.loading = true
      try {
        const res = await getCategoryList({ page: this.currentPage, pageSize: this.pageSize })  // 使用 /category/list 接口
        if (res.code === 200) {
          // 处理分页数据
          const data = res.data;
          if (data && data.records) {
            // 确保每个分类的ID是UUID格式字符串
            this.categoryList = data.records.map(category => ({
              ...category,
              id: category.id || ''  // 确保ID是字符串
            }));
            this.total = data.total;
          } else if (Array.isArray(data)) {
            // 确保每个分类的ID是UUID格式字符串
            this.categoryList = data.map(category => ({
              ...category,
              id: category.id || ''  // 确保ID是字符串
            }));
            this.total = data.length;
          } else {
            this.categoryList = [];
            this.total = 0;
          }
          
          console.log('分类列表:', this.categoryList);
        }
      } catch (error) {
        // 错误消息已由全局拦截器处理，不再重复显示
      } finally {
        this.loading = false
      }
    },

    // 提交表单（新增/编辑）
    async handleSubmit() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          try {
            // 添加或修改分类时，准备必要的数据
            const categoryData = {
              id: this.dialogType === 'add' ? '' : this.categoryForm.id,
              name: this.categoryForm.name,
              productNum: this.categoryForm.productNum || 0,
              total: this.categoryForm.total || 0
            };
            
            // 如果是编辑，保留原有的时间
            if (this.dialogType === 'edit' && this.categoryForm.createTime) {
              categoryData.createTime = this.categoryForm.createTime;
              categoryData.updateTime = new Date().toISOString(); // 更新时间设为当前时间
            } else {
              // 新增时设置创建和更新时间为当前时间
              const now = new Date().toISOString();
              categoryData.createTime = now;
              categoryData.updateTime = now;
            }
            
            console.log('提交分类数据:', categoryData);
            
            // 使用统一的保存接口
            const res = await saveCategory(categoryData);
            
            if (res.code === 200) {
              this.$message.success(this.dialogType === 'add' ? '添加成功' : '修改成功');
              this.dialogVisible = false;
              this.fetchCategories();
            }
          } catch (error) {
            console.error('提交分类信息失败:', error);
            // 错误消息已由全局拦截器处理，不再重复显示
          }
        }
      });
    },

    // 删除分类
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该分类吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 使用字符串格式的UUID作为ID
        const categoryId = row.id;
        console.log('删除分类ID(UUID):', categoryId);
        
        const res = await deleteCategory(categoryId)  // 使用 /category/{categoryId} 接口
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.fetchCategories()
        }
      } catch (error) {
        // 用户取消删除操作不显示错误
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
          // 错误消息已由全局拦截器处理，不再重复显示
        }
      }
    },

    handleAdd() {
      this.dialogType = 'add'
      this.dialogTitle = '添加分类'
      this.categoryForm = {
        name: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑分类'
      
      // 确保分类信息中的ID是UUID格式字符串
      this.categoryForm = { 
        ...row,
        id: row.id  // 确保ID字段是UUID格式字符串
      }
      
      console.log('编辑分类:', this.categoryForm);
      this.dialogVisible = true
    },

    formatDate(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString();
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchCategories();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchCategories();
    }
  },
  created() {
    this.fetchCategories()
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 120px);
  max-width: 100%;
  overflow-x: hidden;
}

.main-card {
  border-radius: 8px;
  margin: 0;
  width: 100%;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #304156;
}

.header-operations {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* Element UI 主题覆盖 */
:deep(.el-button--primary) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background-color: #ff8533;
  border-color: #ff8533;
}

:deep(.el-button--text) {
  color: #ff6b00;
}

:deep(.el-button--text:hover),
:deep(.el-button--text:focus) {
  color: #ff8533;
}

:deep(.el-tag--success) {
  background-color: rgba(255, 107, 0, 0.1);
  border-color: rgba(255, 107, 0, 0.2);
  color: #ff6b00;
}

:deep(.el-tag--info) {
  background-color: rgba(144, 147, 153, 0.1);
  border-color: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.el-card {
  border-radius: 8px;
  margin: 0;
  width: 100%;
  box-sizing: border-box;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.el-table {
  color: #304156;
  width: 100%;
}

.el-table th {
  background-color: #f5f7fa;
  color: #304156;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}
</style> 